package com.aaa.whj.controller;

import com.aaa.whj.entity.Plan;
import com.aaa.whj.entity.Tab_scl_record;
import com.aaa.whj.service.ILoginService;

import com.aaa.whj.service.impl.LoginServiceImpl;

import com.util.LayData;
import com.util.PrintJsonData;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@WebServlet(name = "frontLogin", value = "/frontLogin")
public class FrontLoginServlet extends HttpServlet {

    private final ILoginService iLoginService=new LoginServiceImpl();
    SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd");
    Date date = new Date(System.currentTimeMillis());
    String format = formatter.format(date);
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");

        String tel = req.getParameter("tel");

        String yqcode = req.getParameter("yqcode");

        List<Plan> plans = iLoginService.only_one(yqcode);
        System.out.println("plans = " + plans);

        List<Tab_scl_record> tab_scl_records=iLoginService.only_code(tel);
        System.out.println("tab_scl_records = " + tab_scl_records);

        boolean b = format.compareTo(plans.get(0).getStartTime()) > 0 && format.compareTo(plans.get(0).getEndTime()) < 0;
        System.out.println("b = " + b);
        LayData success = null;
        if (plans.size()!=0&&tab_scl_records.size()==0&&b){
            Tab_scl_record tabSclRecord=new Tab_scl_record(username,tel,yqcode,format);
            int i=iLoginService.addRecord(tabSclRecord);
            //System.out.println("id="+tabSclRecord.getId());
            HttpSession session = req.getSession();
            session.setAttribute("id",tabSclRecord.getId());
            success = LayData.success(plans);
        }else if(plans.size()==0){
            success=LayData.success(null);
            success.setMsg("邀请码出错");
        }else if(!b){
            success=LayData.success(null);
            success.setMsg("现在不在做题的时间范围");
        } else {
            success=LayData.success(null);
            success.setMsg("已经做过题目");
        }

        PrintJsonData.printData(resp,success);


    }
}
